/* global define, JRoll */
(function(window, document, JRoll) {
    'use strict'

    var rAF = window.requestAnimationFrame || window.webkitRequestAnimationFrame ||
    function(callback) {
        setTimeout(callback, 17);
    }

    var TSF = JRoll.utils.TSF;
    var moveTo = JRoll.utils.moveTo;
    var IMG_LOADING = 'data:img/jpg;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAQAAAD9CzEMAAAACXBIWXMAAAsTAAALEwEAmpwYAAADGWlDQ1BQaG90b3Nob3AgSUNDIHByb2ZpbGUAAHjaY2BgnuDo4uTKJMDAUFBUUuQe5BgZERmlwH6egY2BmYGBgYGBITG5uMAxIMCHgYGBIS8/L5UBA3y7xsDIwMDAcFnX0cXJlYE0wJpcUFTCwMBwgIGBwSgltTiZgYHhCwMDQ3p5SUEJAwNjDAMDg0hSdkEJAwNjAQMDg0h2SJAzAwNjCwMDE09JakUJAwMDg3N+QWVRZnpGiYKhpaWlgmNKflKqQnBlcUlqbrGCZ15yflFBflFiSWoKAwMD1A4GBgYGXpf8EgX3xMw8BUNTVQYqg4jIKAX08EGIIUByaVEZhMXIwMDAIMCgxeDHUMmwiuEBozRjFOM8xqdMhkwNTJeYNZgbme+y2LDMY2VmzWa9yubEtoldhX0mhwBHJycrZzMXM1cbNzf3RB4pnqW8xryH+IL5nvFXCwgJrBZ0E3wk1CisKHxYJF2UV3SrWJw4p/hWiRRJYcmjUhXSutJPZObIhsoJyp2V71HwUeRVvKA0RTlKRUnltepWtUZ1Pw1Zjbea+7QmaqfqWOsK6b7SO6I/36DGMMrI0ljS+LfJPdPDZivM+y0qLBOtfKwtbFRtRexY7L7aP3e47XjB6ZjzXpetruvdVrov9VjkudBrgfdCn8W+y/xW+a8P2Bq4N+hY8PmQW6HPwr5EMEUKRilFG8e4xUbF5cW3JMxO3Jx0Nvl5KlOaXLpNRlRmVdas7D059/KY8tULfAqLi2YXHy55WyZR7lJRWDmv6mz131q9uvj6SQ3HGn83G7Skt85ru94h2Ond1d59uJehz76/bsK+if8nO05pnXp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aWVHMoXJDnbh3Z4+S7iACe/tnq4UJT6HdNG9mO9T0km/YMvpMt4/F4kHGiqgFuST9iYfJ6q4QPfA96gDqCPM10Tes83cYs9fgSqCo1PKB04CLMRrBgAAAAldEVYdGRhdGU6Y3JlYXRlADIwMTctMDUtMTZUMTQ6Mzc6NDYrMDg6MDDxu6slAAAAJXRFWHRkYXRlOm1vZGlmeQAyMDE3LTA1LTE2VDE0OjM3OjQ2KzA4OjAwgOYTmQAAAABJRU5ErkJggg==';
    var IMG_STYLE = 'width:1.5em;height:1.5em;display:block;';
    var totalHeight = $('body').offset().height;
    var releaseOffset = 0;
    if (totalHeight == 0) {
        totalHeight = Math.max(document.documentElement.getBoundingClientRect().height, window.screen.height);
        releaseOffset = totalHeight / 13;
    } else
        releaseOffset = totalHeight / 17;

    // 默认选项
    var defaults = {
        iconArrow : "<img style='" + IMG_STYLE + "' src='" + IMG_ARROW + "'>",
        iconLoading : "<img style='" + IMG_STYLE + "' src='" + IMG_LOADING + "'>",
        iconFinish : "<img style='" + IMG_STYLE + "' src='" + IMG_FINISH + "'>",
        textPull : '<span class="sc-text">下拉刷新</span>',
        textRelease : '<span class="sc-text">释放刷新</span>',
        textLoading : '<span class="sc-text">正在加载</span>',
        textFinish : '<span class="sc-text">刷新完成</span>',
        spinning : true, // 应网友要求添加一个选项控制loading时是否旋转icon
        refresh : undefined, // 刷新自定义执行的函数
        releaseOffset : releaseOffset
    }

    // 使iconSpan旋转下来
    function refreshMakeRotate(objEl) {
        objEl.refreshAngle = objEl.refreshAngle + 6 >= 360 ? 0 : objEl.refreshAngle + 6;
        objEl.refreshElIcon.style[TSF] = 'rotateZ(' + objEl.refreshAngle + 'deg)';

        if (objEl.refreshRotating) {
            rAF(function() {
                refreshMakeRotate(objEl);
            })
        } else {
            objEl.refreshElIcon.style[TSF] = 'rotateZ(0deg)';
        }
    }

    /*jroll-pulldown*/
    JRoll.prototype.pulldown = function(params) {
        var me = this;
        var keys = Object.keys(params || {});

        var boxDiv;
        var iconSpan;
        var textSpan;

        var options = $.extend({}, defaults);
        for (var k in keys) {
            options[keys[k]] = params[keys[k]];
        }
        me.options = me.options || {};
        //me.options.releaseOffset = releaseOffset;
        me.options = $.extend({}, me.options, options);

        if (!me.refreshElBox) {
            // 先行加载图片，触发浏览器缓存起来避免刷新时再加载显得不流畅
            document.createElement('div').innerHTML = options.iconArrow + options.iconLoading + options.iconFinish;

            // 创建下拉的div
            boxDiv = document.createElement('div');
            boxDiv.className = 'jroll-plugin-pulldown';
            boxDiv.style.cssText = 'position:absolute;top:-2.75em;width:100%;height:2.75em;line-height:2.75em;font-size:0.75em;text-align:center;';

            iconSpan = document.createElement('span');
            iconSpan.className = 'jroll-plugin-pulldown-icon';
            iconSpan.style.cssText = 'display:inline-block;width:1.5em;height:1.5em;position:absolute;top:0.625em;left:25%;';
            iconSpan.innerHTML = options.iconArrow;
            boxDiv.appendChild(iconSpan);

            textSpan = document.createElement('span');
            textSpan.className = 'jroll-plugin-pulldown-text';
            textSpan.innerHTML = options.textPull;
            boxDiv.appendChild(textSpan);

            me.refreshElBox = boxDiv;
            me.refreshElIcon = iconSpan;
            me.refreshElText = textSpan;
            me.wrapper.appendChild(boxDiv);
        } else {
            boxDiv = me.refreshElBox;
            iconSpan = me.refreshElIcon;
            textSpan = me.refreshElText;
        }
        // 监听滑动事件
        me.on('scroll', function() {
            boxDiv.style[TSF] = me.scroller.style[TSF];

            // 达到一定位置显示释放刷新
            if (!me.refreshLoading) {
                if (me.y > me.options.releaseOffset) {
                    iconSpan.style[TSF] = 'rotateZ(180deg)';
                    textSpan.innerHTML = options.textRelease;
                } else {
                    iconSpan.style[TSF] = 'rotateZ(0deg)';
                    textSpan.innerHTML = options.textPull;
                }
            }
        })
        me.on('touchEnd', function() {
            if (me.y >= me.options.releaseOffset) {
                // 超过44px禁止回弹
                me.y = 0;
                me.options.momentum = false;

                // 刷新
                iconSpan.style[TSF] = 'rotateZ(0deg)';
                iconSpan.innerHTML = options.iconLoading;
                textSpan.innerHTML = options.textLoading;
                setTimeout(function() {
                    me.scrollTo(0, me.options.releaseOffset, 200, true, function() {
                        doRefresh(false);
                    }).minScrollY = me.options.releaseOffset;
                    moveTo(boxDiv, 0, me.options.releaseOffset, 200);

                    me.options.momentum = true;
                }, 10)
            } else if (!me.refreshLoading) {
                moveTo(boxDiv, 0, 0, 200);
            }
        })
        // 执行刷新
        function doRefresh(auto) {
            if (!me.refreshLoading) {
                me.refreshLoading = true;
                me.refreshRotating = true;
                me.refreshAngle = 0;
                if (options.spinning) {
                    refreshMakeRotate(me);
                }
                setTimeout(function() {
                    if ( typeof options.refresh === 'function') {
                        options.refresh(function() {
                            // 完成刷新
                            me.refreshRotating = false;
                            if (auto)
                                iconSpan.style[TSF] = 'rotateZ(0deg)';
                            iconSpan.innerHTML = options.iconFinish;
                            textSpan.innerHTML = options.textFinish;

                            // 收起刷新栏
                            setTimeout(function() {
                                moveTo(boxDiv, 0, 0, 200);

                                me.scrollTo(0, 0, 200, true, function() {
                                    me.refreshLoading = false;
                                    if (auto)
                                        iconSpan.style[TSF] = 'rotateZ(180deg)';
                                    iconSpan.innerHTML = options.iconArrow;
                                    textSpan.innerHTML = options.textPull;
                                }).minScrollY = 0;
                            }, 200);
                        });
                    }
                }, 200);
            }
        }


        me.doRefresh = doRefresh;
        return me;
    }
    /*jroll-pullrefresh*/
    JRoll.prototype.pullrefresh = function(timeout) {
        timeout = timeout || 200;
        var me = this;

        var options = me.options;
        var boxDiv = me.refreshElBox;
        var iconSpan = me.refreshElIcon;
        var textSpan = me.refreshElText;

        iconSpan.style[TSF] = 'rotateZ(0deg)';
        iconSpan.innerHTML = options.iconLoading;
        textSpan.innerHTML = options.textLoading;
        setTimeout(function() {
            me.scrollTo(0, me.options.releaseOffset, 200, true, function() {
                me.doRefresh(true);
            }).minScrollY = me.options.releaseOffset;
            moveTo(boxDiv, 0, me.options.releaseOffset, 200);

            me.options.momentum = true;
        }, timeout)
        return me;
    }

    JRoll.prototype.pulldown.version = '{{version}}';

    // CommonJS/AMD/CMD规范导出JRoll
    if ( typeof module !== 'undefined' && module.exports) {
        module.exports = JRoll;
    }
    if ( typeof define === 'function') {
        define(function() {
            return JRoll;
        })
    }
})(window, document, JRoll)